package my.mybatis.common.util;

public class StringLengthUtil {

	/**
	 * 获取字符串的长度，区分中英文
	 * @param str
	 * @return
	 */
	public static int length(String str) {  
		if (str == null)
			return 0;
		char[] c = str.toCharArray();
		int len = 0;
		for (int i = 0; i < c.length; i++) {
			len++;
			if (!isLetter(c[i])) {
				len++;
			}
		}
		return len;
	} 
	
	/**
	 * 截取字符串长度，算取应该截取的位置，一个中文当两个英文
	 * @param str
	 * @param size (截取位置，如果遇到半个中文，会取全)
	 * @return
	 */
	public static int interceptSize(String str,int size) {  
		if (str == null)
			return 0;
		char[] c = str.toCharArray();
		int len = 0;
		int returnLen = 0;
		for (int i = 0; i < c.length; i++) {
			returnLen++;
			len++;
			if (!isLetter(c[i])) {
				len++;
			}
			if(len >= size)
				return returnLen;
		}
		return returnLen;
	}
	
	public static boolean isLetter(char c) {
		int k = 0x80;
		return c / k == 0 ? true : false;
	}
	
	public static void main(String[] args) {
		String str = "dd发的";
		System.out.println(str.substring(0, interceptSize(str, 4)));
		System.out.println(length(str));
		System.out.println(str.length());
	}
}
